package com.xingzhe.content.service.Impl;

import com.alibaba.fastjson.JSON;
import com.xingzhe.base.exception.CommonError;
import com.xingzhe.base.exception.XingZhePlusException;
import com.xingzhe.content.config.MultipartSupportConfig;
import com.xingzhe.content.feignclient.MediaServiceClient;
import com.xingzhe.content.mapper.CourseBaseMapper;
import com.xingzhe.content.mapper.CourseMarketMapper;
import com.xingzhe.content.mapper.CoursePublishMapper;
import com.xingzhe.content.mapper.CoursePublishPreMapper;
import com.xingzhe.content.model.dto.CourseBaseInfoDto;
import com.xingzhe.content.model.dto.CoursePreviewDto;
import com.xingzhe.content.model.dto.TeachplanDto;
import com.xingzhe.content.model.po.*;
import com.xingzhe.content.service.CourseBaseInfoService;
import com.xingzhe.content.service.CoursePublishService;
import com.xingzhe.content.service.CourseTeacherService;
import com.xingzhe.content.service.TeachPlanService;
import com.xingzhe.messagesdk.model.po.MqMessage;
import com.xingzhe.messagesdk.service.MqMessageService;
import freemarker.cache.ClassTemplateLoader;
import freemarker.template.Configuration;
import freemarker.template.Template;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * 课程发布
 */
@Slf4j
@Service
public class CoursePublishServiceImpl implements CoursePublishService {

    @Autowired
    CourseBaseInfoService courseBaseInfoService;

    @Resource
    CourseBaseMapper courseBaseMapper;


    @Autowired
    TeachPlanService teachplanService;

    @Resource
    CourseMarketMapper courseMarketMapper;

    @Autowired
    CourseTeacherService courseTeacherService;

    @Resource
    CoursePublishMapper coursePublishMapper;

    @Resource
    CoursePublishPreMapper coursePublishPreMapper;

    @Autowired
    MqMessageService mqMessageService;

    @Autowired
    MediaServiceClient mediaServiceClient;

    @Resource
    RedisTemplate redisTemplate;

    @Autowired
    RedissonClient redissonClient;

    @Override
    public CoursePreviewDto getCoursePreviewInfo(Long courseId) {

        //课程基本信息、营销信息
        CourseBaseInfoDto courseBaseInfo = courseBaseInfoService.getCourseBaseInfo(courseId);

        //课程计划信息
        List<TeachplanDto> teachplanTree = teachplanService.findTeachPlanTree(courseId);

        CoursePreviewDto coursePreviewDto = new CoursePreviewDto();
        coursePreviewDto.setCourseBase(courseBaseInfo);
        coursePreviewDto.setTeachplans(teachplanTree);
        return coursePreviewDto;
    }

    @Transactional
    @Override
    public void commitAudit(Long companyId, Long courseId) {
        CourseBaseInfoDto courseBaseInfo = courseBaseInfoService.getCourseBaseInfo(courseId);
        if (courseBaseInfo.getAuditStatus().equals("202003")) {
            XingZhePlusException.cast("当前状态为等待审核，请等审核结束后再进行提交哦~");
        }
        if (!courseBaseInfo.getCompanyId().equals(companyId)) {
            XingZhePlusException.cast("只能提交自己机构的课程哦~");
        }
        if (StringUtils.isEmpty(courseBaseInfo.getPic())) {
            XingZhePlusException.cast("要上传图片哦~");
        }

        //查询课程计划
        List<TeachplanDto> teachPlanTree = teachplanService.findTeachPlanTree(courseId);
        String teachPlanTreeString = JSON.toJSONString(teachPlanTree);
        if (teachPlanTree == null || teachPlanTree.size() == 0) {
            XingZhePlusException.cast("要添加课程计划哦~");
        }

        //将查询到的课程信息，营销信息，课程计划放到课程预发布表
        CoursePublishPre coursePublishPre = new CoursePublishPre();
        //营销信息
        CourseMarket courseMarket = courseMarketMapper.selectById(courseId);
        String courseMaketString = JSON.toJSONString(courseMarket);
        //教师信息
        List<CourseTeacher> teachers = courseTeacherService.findAll(courseId);
        String teachersString = JSON.toJSONString(teachers);

        //将课程基本信息以及部分营销信息拷贝到预发布表
        BeanUtils.copyProperties(courseBaseInfo, coursePublishPre);
        //设置课程营销信息
        coursePublishPre.setMarket(courseMaketString);
        //设置课程计划信息
        coursePublishPre.setTeachplan(teachPlanTreeString);
        //设置课程师资信息
        coursePublishPre.setTeachers(teachersString);
        //设置预发布记录状态,已提交
        coursePublishPre.setStatus("202003");
        //教学机构id
        coursePublishPre.setCompanyId(companyId);
        //提交时间
        coursePublishPre.setCreateDate(LocalDateTime.now());
        CoursePublishPre coursePublishPreUpdate = coursePublishPreMapper.selectById(courseId);
        if (coursePublishPreUpdate == null) {
            //添加课程预发布记录
            coursePublishPreMapper.insert(coursePublishPre);
        } else {
            coursePublishPreMapper.updateById(coursePublishPre);
        }

        //更新课程基本表的审核状态
        CourseBase courseBase = courseBaseMapper.selectById(courseId);
        courseBase.setAuditStatus("202003");
        courseBaseMapper.updateById(courseBase);


    }

    @Transactional
    @Override
    public void publish(Long companyId, Long courseId) {
        //查询预发布表
        CoursePublishPre coursePublishPre = coursePublishPreMapper.selectById(courseId);
        if (coursePublishPre == null) {
            XingZhePlusException.cast("课程还没有提交审核哦~");
        }
        if (!coursePublishPre.getCompanyId().equals(companyId)) {
            XingZhePlusException.cast("只能发布自己机构的课程哦~");
        }
        //查看课程有没有通过审核
        if (!coursePublishPre.getStatus().equals("202004")) {
            XingZhePlusException.cast("课程没有审核通过哦~");
        }

        //保存课程发布信息
        saveCoursePublish(courseId);

        //保存消息表
        saveCoursePublishMessage(courseId);

        //删除课程预发布表对应记录
        coursePublishPreMapper.deleteById(courseId);

        /*//向课程发布表写入或者更新数据
        CoursePublish coursePublish = new CoursePublish();
        BeanUtils.copyProperties(coursePublishPre,coursePublish);
        //先查询课程发布表，有则更新，无则新增
        CoursePublish coursePublishObj = coursePublishMapper.selectById(courseId);
        if (coursePublishObj==null){
            coursePublishMapper.insert(coursePublish);
        }else {
            coursePublishMapper.updateById(coursePublish);
        }
        //向消息表写入数据
        mqMessageService.addMessage("course_publish", String.valueOf(courseId),null,null);
        //将预发布表数据删除
        coursePublishPreMapper.deleteById(courseId);*/
    }

    @Override
    public File generateCourseHtml(Long courseId) {
        File htmlFile = null;
        try {
            //获取freemarker的模板版本
            Configuration configuration = new Configuration(Configuration.getVersion());
            //获取classpath的路径
            /*String classpath = Objects.requireNonNull(this.getClass().getResource("/")).getPath();
            //设置模板路径
            configuration.setDirectoryForTemplateLoading(new File(classpath + "/templates/"));*/
            //更改为如下方式，才能在生产环境运行 (因为上面的方式打成jar包会找不到模板)
            configuration.setTemplateLoader(new ClassTemplateLoader(this.getClass().getClassLoader(), "/templates/"));

            //设置模板编码
            configuration.setDefaultEncoding("utf-8");
            //设置模板文件名称
            Template template = configuration.getTemplate("course_template.ftl");
            //准备模板数据
            CoursePreviewDto coursePreviewInfo = this.getCoursePreviewInfo(courseId);
            //因为静态数据通常有一个用model作为变量名，所以用map保存模板数据
            Map<String, CoursePreviewDto> map = new HashMap<>();
            map.put("model", coursePreviewInfo);
            //静态化
            //第一个参数是模板，第二个参数是模板数据
            //生成html字符串内容，也就是静态化内容
            String html = FreeMarkerTemplateUtils.processTemplateIntoString(template, map);
            //把内容输出到html文件
            //生成输入流（要写的数据）
            InputStream inputStream = IOUtils.toInputStream(html);
            //生成输出流（要写去哪里）
            htmlFile = File.createTempFile("course", ".html");
            FileOutputStream fileOutputStream = new FileOutputStream(htmlFile);
            //使用流将html数据写入文件
            IOUtils.copy(inputStream, fileOutputStream);
        } catch (Exception e) {
            log.error("页面静态化出现问题，课程id:{}", courseId, e);
        }
        return htmlFile;
    }

    @Override
    public void uploadCourseHtml(Long courseId, File file) {
        //将file转为multipartFile
        MultipartFile multipartFile = MultipartSupportConfig.getMultipartFile(file);
        try {
            //远程调用得到返回值
            String upload = mediaServiceClient.upload(multipartFile, "course/" + courseId + ".html");
            if (upload == null) {
                log.debug("远程调用走降级逻辑得到上传结果为null,课程id为：{}", courseId);
                XingZhePlusException.cast("上传静态文件过程中存在异常");
            }
        } catch (Exception e) {
            e.printStackTrace();
            XingZhePlusException.cast("上传静态文件过程中存在异常");
        }
    }


    /**
     * @param courseId 课程id
     * @description 保存课程发布信息
     */
    private void saveCoursePublish(Long courseId) {
        //整合课程发布信息
        //查询课程预发布表
        CoursePublishPre coursePublishPre = coursePublishPreMapper.selectById(courseId);
        if (coursePublishPre == null) {
            XingZhePlusException.cast("课程预发布数据为空");
        }

        CoursePublish coursePublish = new CoursePublish();

        //拷贝到课程发布对象
        BeanUtils.copyProperties(coursePublishPre, coursePublish);
        coursePublish.setStatus("203002");
        CoursePublish coursePublishUpdate = coursePublishMapper.selectById(courseId);
        if (coursePublishUpdate == null) {
            coursePublishMapper.insert(coursePublish);
        } else {
            coursePublishMapper.updateById(coursePublish);
        }
        //更新课程基本表的发布状态
        CourseBase courseBase = courseBaseMapper.selectById(courseId);
        courseBase.setStatus("203002");
        courseBaseMapper.updateById(courseBase);

    }


    /**
     * @param courseId 课程id
     * @description 保存消息表记录
     */
    private void saveCoursePublishMessage(Long courseId) {
        MqMessage mqMessage = mqMessageService.addMessage("course_publish", String.valueOf(courseId), null, null);
        if (mqMessage == null) {
            XingZhePlusException.cast(CommonError.UNKOWN_ERROR);
        }
    }


    /**
     * 根据课程id查询课程发布信息
     *
     * @param courseId
     * @return
     */
    public CoursePublish getCoursePublish(Long courseId) {
        CoursePublish coursePublish = coursePublishMapper.selectById(courseId);
        return coursePublish;
    }

    @Override
    public CoursePublish getCoursePublishCache(Long courseId) {
        //查询缓存
        String jsonString = (String) redisTemplate.opsForValue().get("course:" + courseId);
        if(org.apache.commons.lang.StringUtils.isNotEmpty(jsonString)){
            if(jsonString.equals("null")){
                return null;
            }
            CoursePublish coursePublish = JSON.parseObject(jsonString, CoursePublish.class);
            return coursePublish;
        }else{
            //每门课程设置一个锁
            RLock lock = redissonClient.getLock("coursequerylock:"+courseId);
            //获取锁
            lock.lock();
            try {
                jsonString = (String) redisTemplate.opsForValue().get("course:" + courseId);
                if(org.apache.commons.lang.StringUtils.isNotEmpty(jsonString)){
                    CoursePublish coursePublish = JSON.parseObject(jsonString, CoursePublish.class);
                    return coursePublish;
                }
                System.out.println("=========从数据库查询==========");

                //从数据库查询
                CoursePublish coursePublish = getCoursePublish(courseId);
                redisTemplate.opsForValue().set("course:" + courseId, JSON.toJSONString(coursePublish),1,TimeUnit.DAYS);
                return coursePublish;
            }finally {
                //释放锁
                lock.unlock();
            }
        }



    }
}
